package com.lxs.proxy005.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;

@RestController
public class ProxyController {

    @Autowired
    private RestTemplate restTemplate;

    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    @RequestMapping("/a/**")
    public ResponseEntity<?> proxyRequest(HttpServletRequest request) {
        String originalPath = request.getRequestURI();
        // 移除 /a 前缀
        String targetPath = originalPath.substring(2);

        String targetUrl = "http://localhost:9001" + targetPath;

        // 构建请求
        HttpHeaders headers = new HttpHeaders();
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            if (!headerName.equalsIgnoreCase("host")) {
                headers.add(headerName, request.getHeader(headerName));
            }
        }

        HttpEntity<byte[]> entity = new HttpEntity<>(getRequestBody(request), headers);

        // 发送请求
        try {
            ResponseEntity<byte[]> response = restTemplate.exchange(
                    targetUrl,
                    HttpMethod.valueOf(request.getMethod()),
                    entity,
                    byte[].class
            );

            return response;
        } catch (Exception e) {
            return ResponseEntity.status(500).body("Proxy error: " + e.getMessage());
        }
    }

    private byte[] getRequestBody(HttpServletRequest request) {
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        try {
            InputStream inputStream = request.getInputStream();
            byte[] data = new byte[4096];
            int bytesRead;
            while ((bytesRead = inputStream.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, bytesRead);
            }
            return buffer.toByteArray();
        } catch (IOException e) {
            return new byte[0];
        } finally {
            try {
                buffer.close();
            } catch (IOException e) {
                // 忽略关闭异常
            }
        }
    }
}
